package controller;

import com.alibaba.fastjson.JSON;
import dao.GoodsDao;
import entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/goods")
@Scope("prototype")

public class GoodsController {
    @Autowired
    private GoodsDao goodsDao;

    @RequestMapping(value="/query" ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String query(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=utf-8");
        List<Goods> list = goodsDao.queryGoods();
        request.setAttribute("list",JSON.toJSONString(list));
        return JSON.toJSONString(list);
    }

    @RequestMapping("/queryPage")
    @ResponseBody
    public Map<String,Object> queryPage(@RequestParam(value = "pageNumber",defaultValue = "1",required = false) int pageNumber, @RequestParam(value = "pageSize",defaultValue = "5",required = false) int pageSize){
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> mapResult = new HashMap<String,Object>() ;
        map.put("offset",(pageNumber-1)*pageSize) ;
        map.put("limit",pageSize) ;
        List<Goods> list = goodsDao.queryPage(map);
        mapResult.put("rows",list);
        mapResult.put("total",goodsDao.getCountGoods());
        return mapResult;
    }


    @RequestMapping("/add")
    @ResponseBody
    public Map<String,Object> add(@RequestBody Goods goods, @RequestParam(value = "pageNumber",defaultValue = "1",required = false) int pageNumber, @RequestParam(value = "pageSize",defaultValue = "5",required = false) int pageSize) {
        System.out.println(1);
        int i = goodsDao.addGoods(goods);
        return this.queryPage(pageNumber, pageSize);
    }

    @RequestMapping("/update")
    @ResponseBody
    public int update(Goods goods) {
        int i = goodsDao.updateGoods(goods);
        return i;
    }
}
